﻿using ExchangeClient.Abstractions;
using ExchangeClient.Abstractions.Model;
using Microsoft.Extensions.Logging;
using SyncService.Abstractions.Services;
using SyncService.Core.Model;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Text;
using System.Text.Json.Nodes;
using System.Text.Json;
using System.Threading.Tasks;
using NPOI.POIFS.Crypt.Dsig;
using SyncService.Abstractions.Events;
using System.Security.AccessControl;
using Microsoft.Extensions.Caching.Memory;
using System.Reflection.Emit;
using System.Text.RegularExpressions;

namespace SyncService.Core.Services
{
    [Export(typeof(ISyncService))]
    [ExportMetadata(YdConstants.ID, "assetInstorage")]
    public class AssetInstorageService : AssetSyncServiceBase
    {
        protected override string NotifyGroupName => "";
        private ILogger<AssetInstorageService> _logger = null;
        private IMemoryCache? _cache = null;

        private bool IsNotPush = false;
        public AssetInstorageService() : base(YdConstants.YIDEA, "Esb", "")
        {
        }
        protected override void InitializeContext()
        {
            base.InitializeContext();
            _logger = Resolver.Resolve<ILogger<AssetInstorageService>>();
            _cache = Resolver.Resolve<IMemoryCache>();
        }
        public override void ExecuteCore()
        {
            var data = (AssetSyncEvent)State!;
            try
            {
                _logger.LogInformation("开始处理收货转入库");
                //YideaClient
                Thread.Sleep(10000);
                 var serialNo = data!.Data!["SerialNo"]!.ToString();
                if (serialNo.Substring(0, 3) == "REC")
                {
                    var reciveForm = UserDefines.First(x => x.Name == "收货自定义表单");
                    var reciveData = YideaClient.GetCustomizedFormDatas(formId: reciveForm.Id, new QueryParam()
                    {
                        FilterString = "[{\"field\":\"serialNo\",\"type\":\"input\",\"label\":\"单据号\",\"opt\":\"Equal\",\"val\":\"" + serialNo + "\"}]"
                    }).ToList();
                    if (reciveData.Count > 0)
                    {
                        var recive = JsonNode.Parse(JsonSerializer.Serialize(reciveData[0].Data)).AsObject();
                        string status = recive["status"].ToString();
                        if (status != "2" && status != "4")
                        {
                            _logger.LogInformation("收货单：" + serialNo + "状态不是已完成 return");
                            _logger.LogInformation(JsonSerializer.Serialize(reciveData[0].Data));
                            return;
                        }
                    }
                    else
                    {
                        _logger.LogInformation("没找到收货单：" + serialNo);
                        return;
                    }
                    QueryParam queryParam = new QueryParam();
                    var sadsad = data.Data["operator"]["name"].ToString();
                    string zhongwen = "";

                    // 匹配中文
                    MatchCollection chineseMatches = Regex.Matches(sadsad, @"[\u4E00-\u9FFF]+");
                    foreach (Match match in chineseMatches)
                    {
                        zhongwen += match.Value;
                    }
                    queryParam.FilterString = "Name=" + zhongwen;

                    List<User> users = YideaClient.GetUsers(queryParam).ToList();

                    string userId = "";
                    string userName = "";
                    if (users.Count > 0)
                    {
                        userId = users[0].Id.ToString();
                        userName = users[0].Name.ToString();
                    }
                    AssetInStorage assetInStorage = new AssetInStorage();
                    assetInStorage.Status = 1;
                    #region 字段
                    var companyCodeValueField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "CompanyCode");
                    var companyIdValueField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "CompanyId");
                    var invoiceFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "发票号码");
                    var comapnyCodeFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "公司代码");
                    var centerCodeFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "成本中心码");
                    var applicationSerialNoFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "费控申请单号");
                    var applicationRowFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "费控申请行号");
                    var purchaseOrderFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "采购订单号");
                    var reciveFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "收货单号");
                    var companyNameField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "公司名称");
                    var companyNameInputField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "公司名");
                    var assetcenterNameField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "成本中心名称");
                    var assetcenterNameInputField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "成本中心名");
                    var assetBrandField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "品牌");
                    var assetMasterTopTypeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "资产大类");
                    var assetMasterSourceFiled = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "资产来源");
                    var assetAdressDaleiField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "存放地大类");
                    var assetShopCodeField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "店铺代码");
                    var assetShopNameField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "店铺名称");
                    var assetAdressField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "存放地");
                    var IsGuoZhangField = ExtendFields.First(x => x.ObjectType == 0 && x.Name == "是否过账");

                    var companyMasterCodeField = ExtendFields.First(x => x.ObjectType == 51 && x.Name == "公司代码");
                    var companyMasterNameField = ExtendFields.First(x => x.ObjectType == 51 && x.Name == "公司名称");

                    var centerCodeField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心");
                    var centerNameField = ExtendFields.First(x => x.ObjectType == 52 && x.Name == "成本中心名称");

                    var assetListCodeField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "资产列表");
                    var assetQueryCodeField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "资产列表query");
                    var manualReceiptNumberField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "手工收货单号");

                    var addressDaLeiField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "存放地大类");
                    var shopCodeField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "店铺代码");
                    var shopNameField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "店铺名称");
                    var addressrField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "存放地");

                    var company = UserDefines.First(x => x.Name == "公司主数据");
                    var center = UserDefines.First(x => x.Name == "成本中心");
                    #endregion
                    var mainform = new YideaMainFormAssetInStorage()
                    {
                        Date = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 00:00:00")),
                        CreateDate = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 00:00:00")),
                        Creator = new JsonObject
                        {
                            ["value"] = userId,
                            ["label"] = userName
                        },
                        OwnCompany = new JsonObject
                        {
                            ["value"] = companyIdValueField.FieldId,//修改值
                            ["code"] = companyCodeValueField.FieldId,//修改值
                            ["label"] = "宝胜集团",
                            ["type"] = "departmentName"
                        },
                        Source = new JsonObject
                        {

                            ["value"] = "1",
                            ["label"] = "购入",
                            ["color"] = new JsonObject
                            {
                                ["backgroundColor"] = "#577eff",
                                ["foreColor"] = "#ffffff"

                            },
                        },
                        ReceiptSerialNumber = serialNo,
                        ManualReceiptNumber = data!.Data![manualReceiptNumberField.FieldId].ToString(),
                        FlowFlag = "1"
                    };
                    assetInStorage.FormJson = JsonSerializer.Serialize(mainform);
                    var assetList = new JsonArray();
                    var assetInStorageList = data!.Data![assetListCodeField.FieldId].AsArray();
                    #region 字段
                    var EquipmentSn = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "设备序列号");
                    var assetNameField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "资产名称");
                    var assetTypeCodeField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "资产编码");
                    var numberFiled = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "资产数量");
                    var assetQueryField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "资产明细");
                    var districeFiled = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "资产区域");
                    var recivedateField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "收货日期");
                    var reciveAmountField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "收货金额");


                    var instorageCompanyCodeField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "公司代码");
                    var instorageCompanyNameField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "公司名称");
                    var instorageCenterCodeField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "成本中心代码");
                    var instorageCenterNameField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "成本中心名称");

                    var fkApplicationSerialNoField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "费控申请单号");
                    var fkApplicationRowField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "费控申请行号");
                    var purchaseOrderNoField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "采购订单号");
                    var vendorField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "供应商");

                    var brandField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "品牌");
                    var specField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "规格型号");
                    var assetTopTypeField = ExtendFields.First(x => x.ObjectType == 53 && x.Name == "资产大类");
                    #endregion
                    foreach (var asset in assetInStorageList)
                    {
                        var assetTypeCode = "";
                        if (asset[assetTypeCodeField.FieldId] != null || asset[assetQueryCodeField.FieldId][assetTypeCodeField.FieldId] != null)
                        {
                            assetTypeCode = asset[assetTypeCodeField.FieldId] == null ? asset[assetQueryCodeField.FieldId][assetTypeCodeField.FieldId].ToString() : asset[assetTypeCodeField.FieldId].ToString();
                        }

                        var brand = "";
                        if (asset[brandField.FieldId] != null || asset[assetQueryCodeField.FieldId][brandField.FieldId] != null)
                        {
                            brand = asset[brandField.FieldId] == null ? asset[assetQueryCodeField.FieldId][brandField.FieldId].ToString() : asset[brandField.FieldId].ToString();
                        }
                        var spec = "";
                        if (asset[specField.FieldId] != null || asset[assetQueryCodeField.FieldId][specField.FieldId] != null)
                        {
                            spec = asset[specField.FieldId] == null ? asset[assetQueryCodeField.FieldId][specField.FieldId].ToString() : asset[specField.FieldId].ToString();
                        }
                        var assetNumber = asset[numberFiled.FieldId] == null ? asset[assetQueryCodeField.FieldId][numberFiled.FieldId].ToString() : asset[numberFiled.FieldId].ToString();
                        var number = int.Parse(assetNumber);
                        var assetTypeName = GetAssetTypeByCode(assetTypeCode);

                        JsonObject companyDetail = new JsonObject();
                        var instorageCompanyCode = asset[instorageCompanyCodeField.FieldId] == null ? asset[assetQueryCodeField.FieldId][instorageCompanyCodeField.FieldId].ToString() : asset[instorageCompanyCodeField.FieldId].ToString();
                        var instorageCompanyName = asset[instorageCompanyNameField.FieldId] == null ? asset[assetQueryCodeField.FieldId][instorageCompanyNameField.FieldId].ToString() : asset[instorageCompanyNameField.FieldId].ToString();
                        var companyData = YideaClient.GetCustomizedFormDatas(formId: company.Id, new QueryParam()
                        {
                            FilterString = "[{\"field\":\"" + companyMasterCodeField.FieldId + "\",\"type\":\"input\",\"label\":\"公司代码\",\"opt\":\"Equal\",\"val\":\"" + instorageCompanyCode + "\"}]"
                        }).ToList();
                        if (companyData.Count > 0)
                        {
                            companyDetail = JsonNode.Parse(JsonSerializer.Serialize(companyData[0].Data)).AsObject();
                            companyDetail.Remove("dataJson");
                            companyDetail[companyMasterCodeField.FieldId] = instorageCompanyCode;
                            companyDetail[companyMasterNameField.FieldId] = instorageCompanyName;
                        }

                        JsonObject centerDetail = new JsonObject();
                        var instorageCenterCode = asset[instorageCenterCodeField.FieldId] == null ? asset[assetQueryCodeField.FieldId][instorageCenterCodeField.FieldId].ToString() : asset[instorageCenterCodeField.FieldId].ToString();
                        var instorageCenterName = asset[instorageCenterNameField.FieldId] == null ? asset[assetQueryCodeField.FieldId][instorageCenterNameField.FieldId].ToString() : asset[instorageCenterNameField.FieldId].ToString();
                        var centerData = YideaClient.GetCustomizedFormDatas(formId: center.Id, new QueryParam()
                        {
                            FilterString = "[{\"field\":\"" + centerCodeField.FieldId + "\",\"type\":\"input\",\"label\":\"成本中心\",\"opt\":\"Equal\",\"val\":\"" + instorageCenterCode + "\"}]"
                        }).ToList();
                        if (centerData.Count > 0)
                        {
                            centerDetail = JsonNode.Parse(JsonSerializer.Serialize(centerData[0].Data)).AsObject();
                            centerDetail.Remove("dataJson");
                            centerDetail[centerCodeField.FieldId] = instorageCenterCode;
                            centerDetail[centerNameField.FieldId] = instorageCenterName;
                        }
                        //店铺，存放地
                        string adressDalei = "", shopCode = "", adressDataJson = "\"\"", shopDataJson = "\"\"";
                        if ((asset[addressDaLeiField.FieldId] != null && asset[addressDaLeiField.FieldId].ToString() != "") || (asset[assetQueryCodeField.FieldId][addressDaLeiField.FieldId] != null && asset[assetQueryCodeField.FieldId][addressDaLeiField.FieldId].ToString() != ""))
                        {
                            adressDalei = asset[addressDaLeiField.FieldId] == null ? asset[assetQueryCodeField.FieldId][addressDaLeiField.FieldId]["label"].ToString() : asset[addressDaLeiField.FieldId]["label"].ToString();
                            var adressDaleiValue = asset[addressDaLeiField.FieldId] == null ? asset[assetQueryCodeField.FieldId][addressDaLeiField.FieldId]["value"].ToString() : asset[addressDaLeiField.FieldId]["value"].ToString();
                            adressDataJson = "{\"id\":\"" + adressDaleiValue + "\",\"value\":\"" + adressDaleiValue + "\",\"label\":\"" + adressDalei + "\"}";
                        }
                        if ((asset[shopCodeField.FieldId] != null && asset[shopCodeField.FieldId].ToString() != "") || (asset[assetQueryCodeField.FieldId][shopCodeField.FieldId] != null && asset[assetQueryCodeField.FieldId][shopCodeField.FieldId].ToString() != ""))
                        {
                            shopCode = asset[shopCodeField.FieldId] == null ? asset[assetQueryCodeField.FieldId][shopCodeField.FieldId]["label"].ToString() : asset[shopCodeField.FieldId]["label"].ToString();
                            var shopCodeValue = asset[shopCodeField.FieldId] == null ? asset[assetQueryCodeField.FieldId][shopCodeField.FieldId]["value"].ToString() : asset[shopCodeField.FieldId]["value"].ToString();
                            shopDataJson = "{\"id\":\"" + shopCodeValue + "\",\"value\":\"" + shopCodeValue + "\",\"label\":\"" + shopCode + "\"}";
                        }
                        var assetTopType = asset[assetTopTypeField.FieldId] == null ? asset[assetQueryCodeField.FieldId][assetTopTypeField.FieldId].ToString() : asset[assetTopTypeField.FieldId].ToString();
                        for (int i = 0; i < number; i++)
                        {
                            var EqSnData = "";
                            if (assetTypeCode == "GE01" || assetTypeCode == "LE01" || assetTypeCode == "LE02" || assetTypeCode == "GE02" || assetTypeCode == "LE14" || assetTypeCode == "GE14" || assetTypeCode == "LE29" || assetTypeCode == "GE29")
                            {
                                var EqSn = asset[EquipmentSn.FieldId].ToString();
                                string[] result = EqSn.Split(',');
                                EqSnData = result[i];
                            }

                            var name = asset[assetNameField.FieldId] == null ? asset[assetQueryCodeField.FieldId][assetNameField.FieldId].ToString() : asset[assetNameField.FieldId].ToString();
                            var shopname = asset[shopNameField.FieldId] == null ? (asset[assetQueryCodeField.FieldId][shopNameField.FieldId] == null ? "" : asset[assetQueryCodeField.FieldId][shopNameField.FieldId].ToString()) : asset[shopNameField.FieldId].ToString();
                            var address = asset[addressrField.FieldId] == null ? (asset[assetQueryCodeField.FieldId][addressrField.FieldId] == null ? "" : asset[assetQueryCodeField.FieldId][addressrField.FieldId].ToString()) : asset[addressrField.FieldId].ToString();

                            var assetdistrictName = asset[districeFiled.FieldId] == null ? asset[assetQueryCodeField.FieldId][districeFiled.FieldId]["label"].ToString() : asset[districeFiled.FieldId]["label"].ToString();
                            var assetAmount = asset[reciveAmountField.FieldId] == null ? asset[assetQueryCodeField.FieldId][reciveAmountField.FieldId].ToString() : asset[reciveAmountField.FieldId].ToString();
                            var assetVendor = asset[vendorField.FieldId] == null ? asset[assetQueryCodeField.FieldId][vendorField.FieldId].ToString() : asset[vendorField.FieldId].ToString();
                            var applicationSerialNo = asset[fkApplicationSerialNoField.FieldId] == null ? asset[assetQueryCodeField.FieldId][fkApplicationSerialNoField.FieldId].ToString() : asset[fkApplicationSerialNoField.FieldId].ToString();
                            var applicationRow = asset[fkApplicationRowField.FieldId] == null ? asset[assetQueryCodeField.FieldId][fkApplicationRowField.FieldId].ToString() : asset[fkApplicationRowField.FieldId].ToString();
                            var purchaseOrder = asset[purchaseOrderNoField.FieldId] == null ? asset[assetQueryCodeField.FieldId][purchaseOrderNoField.FieldId].ToString() : asset[purchaseOrderNoField.FieldId].ToString();
                            assetList.Add(new JsonObject
                            {

                                ["name"] = name,
                                ["specs"] = spec,
                                ["SN"] = EqSnData,
                                ["EXT_" + assetBrandField.FieldId] = brand,
                                ["assetTypeName"] = assetTypeName,
                                ["districtName"] = assetdistrictName,
                                ["supervisor"] = data!.Data["operator"]["name"].ToString(),
                                ["supervisorNo"] = data!.Data["operator"]["employeeno"].ToString(),
                                ["purchaseDate"] = data!.Data[recivedateField.FieldId].ToString(),
                                ["amount"] = assetAmount,
                                ["EXT_" + assetMasterTopTypeField.FieldId + "_VALUE"] = assetTopType,
                                ["EXT_" + assetAdressDaleiField.FieldId + "_VALUE"] = adressDalei,
                                ["EXT_" + assetShopCodeField.FieldId + "_VALUE"] = shopCode,
                                ["EXT_" + assetMasterTopTypeField.FieldId] = new JsonObject
                                {
                                    ["value"] = assetTopType,
                                    ["label"] = assetTopType,
                                    ["color"] = new JsonObject
                                    {
                                        ["backgroundColor"] = "#52a8ff",
                                        ["foreColor"] = "#ffffff"
                                    }
                                },
                                ["EXT_" + assetMasterSourceFiled.FieldId + "_VALUE"] = "购入",
                                ["EXT_" + assetMasterSourceFiled.FieldId] = new JsonObject
                                {
                                    ["value"] = "购入",
                                    ["label"] = "购入",
                                    ["color"] = new JsonObject
                                    {
                                        ["backgroundColor"] = "#4fbbe0",
                                        ["foreColor"] = "#ffffff"
                                    }
                                },
                                ["EXT_" + assetShopNameField.FieldId] = shopname,
                                ["EXT_" + assetAdressField.FieldId] = address,
                                ["EXT_" + invoiceFiled.FieldId] = "0",
                                ["EXT_" + comapnyCodeFiled.FieldId] = instorageCompanyCode,
                                ["EXT_" + assetcenterNameInputField.FieldId] = instorageCenterName,
                                ["EXT_" + companyNameInputField.FieldId] = instorageCompanyName,
                                ["EXT_" + centerCodeFiled.FieldId] = instorageCenterCode,
                                ["EXT_" + applicationSerialNoFiled.FieldId] = applicationSerialNo,
                                ["EXT_" + applicationRowFiled.FieldId] = applicationRow,
                                ["EXT_" + purchaseOrderFiled.FieldId] = purchaseOrder,
                                ["EXT_" + reciveFiled.FieldId] = serialNo,
                                ["dataJson"] = "{\"" + assetAdressDaleiField.FieldId + "\":" + adressDataJson + ",\"" + assetShopCodeField.FieldId + "\":" + shopDataJson + ",\"" + assetAdressField.FieldId + "\":\"" + address + "\",\"" + assetShopNameField.FieldId + "\":\"" + shopname + "\",\"" + assetMasterTopTypeField.FieldId + "\":{\"value\":\"" + assetTopType + "\",\"label\":\"" + assetTopType + "\",\"color\":{\"backgroundColor\":\"#52a8ff\",\"foreColor\":\"#ffffff\"}},\"" + assetMasterSourceFiled.FieldId + "\":{\"value\":\"购入\",\"label\":\"购入\",\"color\":{\"backgroundColor\":\"#4fbbe0\",\"foreColor\":\"#ffffff\"}},\"" + assetBrandField.FieldId + "\":\"" + brand + "\",\"" + invoiceFiled.FieldId + "\":\"0\",\"" + companyNameField.FieldId + "\":" + companyDetail + ",\"" + assetcenterNameField.FieldId + "\":" + centerDetail + ",\"" + comapnyCodeFiled.FieldId + "\":\"" + instorageCompanyCode + "\",\"" + companyNameInputField.FieldId + "\":\"" + instorageCompanyName + "\",\"" + centerCodeFiled.FieldId + "\":\"" + instorageCenterCode + "\",\"" + assetcenterNameInputField.FieldId + "\":\"" + instorageCenterName + "\",\"" + applicationSerialNoFiled.FieldId + "\":\"" + applicationSerialNo + "\",\"" + applicationRowFiled.FieldId + "\":\"" + applicationRow + "\",\"" + purchaseOrderFiled.FieldId + "\":\"" + purchaseOrder + "\",\"" + reciveFiled.FieldId + "\":\"" + serialNo + "\",\"version\":\"\"}",

                                ["vendor"] = assetVendor
                            });
                        }
                    }
                    _logger.LogInformation("收货转入库资产列表：" + JsonSerializer.Serialize(assetList));
                    _logger.LogInformation("收货转入库资产formjson：" + JsonSerializer.Serialize(mainform));
                    assetInStorage.AssetList = assetList;
                    Thread.Sleep(10000);
                    JsonObject ret = YideaClient.AddAssetInStorage(assetInStorage);
                    _logger.LogInformation("收货转入库处理结果" + ret);
                }

                _logger.LogInformation("结束处理收货转入库");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理收货转入库异常");
            }

        }
        private List<AssetType> GetAssetTypeFromCache()
        {
            _cache.TryGetValue("AssetType", out var assetValue);
            List<AssetType> assetTypeList = new List<AssetType>();
            if (assetValue != null)
            {
                assetTypeList = ((IEnumerable<dynamic>)assetValue).Select(item => new AssetType
                {
                    Id = item.Id,
                    Name = item.Name,
                    Hierarchy = item.Hierarchy,
                    Code = item.Code
                }).ToList();
            }
            else
            {
                assetTypeList = FromClient.GetAssetTypes(null).ToList();
                _cache.Set("AssetType", assetTypeList, DateTime.Now.AddMinutes(5));
            }
            return assetTypeList;
        }
        protected string GetAssetTypeByCode(string assetTypeCode)
        {

            List<AssetType> assetTypeList = GetAssetTypeFromCache();

            var assetType = assetTypeList.Where(e => e.Code == assetTypeCode).FirstOrDefault();
            var hierarchy = assetType.Hierarchy.Split('|');
            string hierarchyName = "";
            foreach (var item in hierarchy)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    var topAssetType = assetTypeList.Where(e => e.Id == int.Parse(item)).FirstOrDefault();
                    if (topAssetType != null)
                    {
                        hierarchyName += topAssetType.Name + "/";
                    }
                }
            }
            if (!string.IsNullOrEmpty(hierarchyName))
            {
                hierarchyName = hierarchyName.Substring(0, hierarchyName.Length - 1);
            }
            return hierarchyName;

        }
    }
}
